package com.gdzl_hadoop.common;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang.StringUtils;
import org.hsqldb.RangeGroup;

import java.io.*;
import java.net.URLDecoder;

/**
 * Created by 1032019725 on 2017/12/5.
 */
public class ConnectToLinux {

    private static String DEFAULTCHART = "UTF-8";
    private static String OUTCHARSET = "";
    private static Connection conn;
    InputStream resStream = null;
    private String ip;
    private String userName;
    private String userPwd;
    private String linuxTmpDir;

    public ConnectToLinux(String ip, String userName, String userPwd) {
        this.ip = ip;
        this.userName = userName;
        this.userPwd = userPwd;
    }

    public ConnectToLinux() {

    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     * @author Ickes
     * @since V0.1
     */
    public static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void setCharset(String charset) {
        DEFAULTCHART = charset;
    }

    public InputStream getresStream() {

        return this.resStream;
    }

    /**
     * 上传指定文件到Hadoop集群
     *
     * @param localFile       待上传的文件
     * @param remoteTargetDir 目的地址/目录
     * @return 上传成功（boolean true）/失败（boolean false）
     */
    public boolean uploadFileToRemote(String localFile, String remoteTargetDir) {
        try {

            SCPClient scpClient = conn.createSCPClient();

            File item = new File(localFile);
            if (item.isFile()) {
                scpClient.put(URLDecoder.decode(localFile, "UTF-8"), remoteTargetDir);
            }
            System.out.println("LOCAL->LINUX 文件传输完成:");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            //close();
        }

    }

    /**
     * @param
     * @param
     * @param hdfsPath 上传至hdfs中的目录
     *                 <p>
     *                 注意：这里首先将文件上传至Linux /home/hadoop/tmp/  再将文件上传至hdfs中的/tmp
     * @throws IOException
     * @throws InterruptedException
     */
    public boolean uploadFileToHdfs(String localFile, String fileName, String remoteTargetDir, String hdfsPath) throws IOException {
        if (uploadFileToRemote(localFile, remoteTargetDir)) {
            try {
                System.out.println(remoteTargetDir + "/" + fileName);
                executeShell("hadoop fs -put " + remoteTargetDir + "/" + fileName + " " + hdfsPath);
                Thread.sleep(3000);
                System.out.println("LINUX->HADOOP 文件传输hdfs完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //      executeShell("rm -r " + remoteTargetDir + "/"+fileName);
            }
            return true;
        }
        return false;
    }

    /**
     * 远程登录linux的主机
     *
     * @return 登录成功返回true，否则返回false
     * @author Ickes
     * @since V0.1
     */
    public Boolean login() {
        boolean flg = false;
        try {
            conn = new Connection(ip);
            conn.connect();//连接

            flg = conn.authenticateWithPassword(userName, userPwd);//认证
            if (flg) {
                System.out.println("认证成功！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (IllegalStateException e) {
            if (e.getMessage() == "Connection is already authenticated!")
                return true;
            return false;
        }
        return flg;
    }

    /**
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String execute(String cmd) {
        return execute(cmd, "GB2312");
    }

    public String execute(String cmd, String charset) {
        String result = "";
        resStream = null;
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                // result = new String(result.getBytes("ISO-8859-1"),"UTF-8");
                resStream = session.getStdout();
                result = processStdout(session.getStdout(), charset);
                //result=processStdout(session.getStdout(),DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), charset);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String executeShell(String cmd) {
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.requestPTY("bash");
                session.startShell();
                PrintWriter out = new PrintWriter(session.getStdin());
                out.println(cmd);
                out.println("exit");
                out.close();
                Thread.sleep(3000);
                session.close();
                conn.close();

            } else {
                return "error";
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param cmd 即将执行的命令
     * @return 命令执行成功后返回的结果值，如果命令执行失败，返回空字符串，不是null
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String executeSuccess(String cmd) {
        String result = "";
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
}



